package com.longxiao.validator.parser;


import com.longxiao.validator.ValidResult;
import com.longxiao.validator.anno.ValiString;

import java.lang.annotation.Annotation;

/**
 * Created by houhongwei on 2017/5/12.
 */
public class ValiStringParser extends Parser {

    private static final int LEN_SKIP = -999;
    private static final String SKIP = "";

    @Override
    protected ValidResult doValid(Object value, Annotation annotation) {
        ValiString anno = ((ValiString) annotation);
        String s = null;
        if (value.getClass().isArray()) {
            s = ((String[]) value)[0];
        }
        if (value instanceof String) {
            s = (String) value;
        }
        // 最小长度
        int min = anno.minLen();
        if (!isSkip(min)) {
            if (s.length() < min) {
                return ValidResult.createFail(anno.err());
            }
        }
        // 最大长度
        int max = anno.maxLen();
        if (!isSkip(max)) {
            if (s.length() > max) {
                return ValidResult.createFail(anno.err());
            }
        }
        // 可选值
        String[] arrRef = anno.ref();
        String tmp = arrRef[0];
        if (!isSkip(tmp)) {
            int tmpCount = 0;
            for (String ref : arrRef) {
                if (ref.equals(s)) {
                    tmpCount ++;
                    break;
                }
            }
            if (tmpCount == 0) {
                return ValidResult.createFail(anno.err());
            }
        }

        // 正则表达式
        String regex = anno.regex();
        if (!isSkip(regex)) {
            if (!s.matches(regex)) {
                return ValidResult.createFail(anno.err());
            }
        }

        // 都验证过了，返回成功
        return ValidResult.createSucc();
    }

    @Override
    public Class getAnno() {
        return ValiString.class;
    }

    @Override
    protected boolean isRequired(Annotation annotation) {
        return ((ValiString) annotation).required();
    }

    @Override
    protected String getErr(Annotation annotation) {
        return ((ValiString) annotation).err();
    }

    // 是否跳过
    private boolean isSkip(String value) {
        if (SKIP.equals(value)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    // 是否跳过
    private boolean isSkip(int value) {
        if (LEN_SKIP == value) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
